//
//  RDBloodSugarDBManager.m
//  ReverseDiabetes
//
//  Created by 王佩璇 on 2024/8/27.
//

#import "RDBloodSugarDBManager.h"
#define TableName(tablename) [NSString stringWithFormat:@"%@",tablename]
#define kDocumentPath (NSString *)[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
static NSString *dbFileName = @"diabetes.sqlite";
@implementation RDBloodSugarDBManager


static RDBloodSugarDBManager *_instance = nil;

#pragma mark =============== init ===============
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_instance == nil) {
            _instance = [[RDBloodSugarDBManager alloc] init];
        }
    });
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}

- (instancetype)init {
    if(self = [super init]) {
#if TARGET_IPHONE_SIMULATOR
        [self.queue inDatabase:^(FMDatabase * _Nonnull db) {}];
#else
        // 加密数据库文件
        NSString *encryptKey = @"RDBloodSugarDBManagerKey";
        [self.queue inDatabase:^(FMDatabase * _Nonnull db) {
            // 加密数据库文件
            [db setKey:encryptKey];
        }];
#endif
        
        [self createAllTable];
    }
    return self;
}
- (FMDatabaseQueue *)queue {
    if (!_queue) {
        NSString *dbpath = [self getDBPath];
        NSLog(@"-----%@",dbpath);
        ///创建数据库及线程队列
        _queue = [FMDatabaseQueue databaseQueueWithPath:dbpath];
    }
    return _queue;
}

- (NSString *)getDBPath {
    NSString *docPath = kDocumentPath;
    NSString *filePath = [docPath stringByAppendingPathComponent:dbFileName];
    
    [[NSFileManager defaultManager] setAttributes:[NSDictionary dictionaryWithObject:NSFileProtectionNone forKey:NSFileProtectionKey] ofItemAtPath:filePath error:nil];
    
    return filePath;
}

- (void)createAllTable {
    [self createBloodSugarTable];
}

#pragma mark =============== BloodSugar ===============
- (void)createBloodSugarTable {
    NSString *sql = [NSString stringWithFormat:@"create table if not exists %@ (%@ INTEGER PRIMARY KEY, %@ varchar, %@ varchar, %@ datetime, %@ datetime)",
                            TableName(Table_BloodSugar),
                     Table_BloodSugar_Blood_Sugar_Id,
                     Table_BloodSugar_Blood_Sugar_Value,
                     Table_BloodSugar_Blood_Sugar_Tag,
                     Table_BloodSugar_Blood_create_time,
                     Table_BloodSugar_Blood_recording_time
    ];
        
        __block BOOL executeFlag = NO;
        [_queue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
            executeFlag = [db executeUpdate:sql];
            if(!executeFlag) {
                *rollback = YES;
                return;
            }
        }];
}


- (void)saveBloodSugar:(RDBloodSugar *)bloodSugar{
    @synchronized (self) {
        __block BOOL result = NO;
        __block BOOL insertFlag = YES;
        
         // 新增 or 更新
         NSString *sql = [NSString stringWithFormat:@"select count(*) from %@ where %@ = ?",
                          TableName(Table_BloodSugar),
                          Table_BloodSugar_Blood_Sugar_Id];
         [_queue inDatabase:^(FMDatabase *db) {
             int count = [db intForQuery:sql, bloodSugar.blood_sugar_id];
             
             if (0 < count) {
                 insertFlag = NO;
             }
         }];
       
         
         if (insertFlag) {
            
             // 新增
             sql = [NSString stringWithFormat:@"insert into %@ (%@, %@, %@, %@) values (?, ?, ?, ?)",
                    TableName(Table_BloodSugar),
                    
                    Table_BloodSugar_Blood_Sugar_Value,
                    Table_BloodSugar_Blood_create_time,
                    Table_BloodSugar_Blood_recording_time,
                    Table_BloodSugar_Blood_Sugar_Tag
             ];
             
             [_queue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
                 result = [db executeUpdate:sql, bloodSugar.blood_sugar_value,bloodSugar.create_time,bloodSugar.recording_time,bloodSugar.blood_sugar_tag];
                 if(!result) {
                     *rollback = YES;
                     return;
                 }
             }];
         }
         else {
             // 更新
             sql = [NSString stringWithFormat:@"update %@ set %@ = ?, %@ = ? %@ = ? , %@ = ? where %@ = ?",
                    TableName(Table_BloodSugar),
                    Table_BloodSugar_Blood_Sugar_Value,
                    Table_BloodSugar_Blood_create_time,
                    Table_BloodSugar_Blood_recording_time,
                    Table_BloodSugar_Blood_Sugar_Tag,
                    Table_BloodSugar_Blood_Sugar_Id];
             
             [_queue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
                 result = [db executeUpdate:sql,bloodSugar.blood_sugar_value,bloodSugar.create_time,bloodSugar.recording_time,bloodSugar.blood_sugar_tag,bloodSugar.blood_sugar_id];
                 if(!result) {
                     *rollback = YES;
                     return;
                 }
             }];
         }
     }
}

- (NSMutableArray *)getBloodSugarHistory{
    @synchronized (self) {
        NSMutableArray *dataArray = [NSMutableArray array];
        
        NSString *sql = [NSString stringWithFormat:@"select * from %@ order by %@ desc",
                         TableName(Table_BloodSugar),
                         Table_BloodSugar_Blood_create_time
        ];
        [_queue inDatabase:^(FMDatabase *db) {
            FMResultSet *rs = [db executeQuery:sql];
            
            while ([rs next]) {
                @autoreleasepool {

                    RDBloodSugar *model = [RDBloodSugar new];

                   
                    if (![rs columnIsNull:Table_BloodSugar_Blood_Sugar_Value]) {
                        model.blood_sugar_value = [rs stringForColumn:Table_BloodSugar_Blood_Sugar_Value];
                    }
                    
                    if (![rs columnIsNull:Table_BloodSugar_Blood_create_time]) {
                        model.create_time = [rs stringForColumn:Table_BloodSugar_Blood_create_time];
                    }
                    
                    if (![rs columnIsNull:Table_BloodSugar_Blood_recording_time]) {
                        model.recording_time = [rs stringForColumn:Table_BloodSugar_Blood_recording_time];
                    }
                    
                    if (![rs columnIsNull:Table_BloodSugar_Blood_Sugar_Tag]) {
                        model.blood_sugar_tag = [NSNumber numberWithInt:[rs stringForColumn:Table_BloodSugar_Blood_Sugar_Tag].intValue];
                    }
                    if (![rs columnIsNull:Table_BloodSugar_Blood_Sugar_Id]) {
                        model.blood_sugar_id =  [NSNumber numberWithInt:[rs stringForColumn:Table_BloodSugar_Blood_Sugar_Id].intValue];
                    }
                    [dataArray addObject:model];
                }
            }
            if (rs) {
                [rs close];
            }
        }];
        
        return dataArray;
    }
}
- (NSMutableArray *)getBloodSugarByRecordingTime:(NSString *)recording_time{
    @synchronized (self) {
        NSMutableArray *dataArray = [NSMutableArray array];
        
        NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@=? order by %@ desc",
                         TableName(Table_BloodSugar),
                         Table_BloodSugar_Blood_recording_time,
                         Table_BloodSugar_Blood_create_time
        ];
        [_queue inDatabase:^(FMDatabase *db) {
            FMResultSet *rs = [db executeQuery:sql,recording_time];
            
            while ([rs next]) {
                @autoreleasepool {

                    RDBloodSugar *model = [RDBloodSugar new];

                   
                    if (![rs columnIsNull:Table_BloodSugar_Blood_Sugar_Value]) {
                        model.blood_sugar_value = [rs stringForColumn:Table_BloodSugar_Blood_Sugar_Value];
                    }
                    
                    if (![rs columnIsNull:Table_BloodSugar_Blood_create_time]) {
                        model.create_time = [rs stringForColumn:Table_BloodSugar_Blood_create_time];
                    }
                    
                    if (![rs columnIsNull:Table_BloodSugar_Blood_recording_time]) {
                        model.recording_time = [rs stringForColumn:Table_BloodSugar_Blood_recording_time];
                    }
                    
                    if (![rs columnIsNull:Table_BloodSugar_Blood_Sugar_Id]) {
                        model.blood_sugar_id =  [NSNumber numberWithInt:[rs stringForColumn:Table_BloodSugar_Blood_Sugar_Id].intValue];
                    }
                    
                    
                    if (![rs columnIsNull:Table_BloodSugar_Blood_Sugar_Tag]) {
                        model.blood_sugar_tag = [NSNumber numberWithInt:[rs stringForColumn:Table_BloodSugar_Blood_Sugar_Tag].intValue];
                    }
     
                    [dataArray addObject:model];
                }
            }
            if (rs) {
                [rs close];
            }
        }];
        
        return dataArray;
    }
}


- (void)deleteBloodSugar:(RDBloodSugar *)bloodSugar{
    
    @synchronized (self) {
        __block BOOL result = NO;
        
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@ = ?",
                         TableName(Table_BloodSugar),
                         Table_BloodSugar_Blood_Sugar_Id];
        
        [_queue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
            result = [db executeUpdate:sql, bloodSugar.blood_sugar_id];
           
                
            
              
           
        }];
    }
    
}
@end
